﻿using S7.Net;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp11
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        //实例化一个新的plc对象，传入的参数为，plc型号，ip地址，端口号，槽位号
        Plc myplc = new Plc(CpuType.S71500, "172.28.101.24", 0, 1);

        //实例化一个PlcData类，PlcData是自定义的一个类
        PlcData myplcData = new PlcData();
        //用于准确的测量运行时间
        Stopwatch stopwatch = new Stopwatch();
        private void button1_Click(object sender, System.EventArgs e)
        {
            //myplc.Open();//打开PLC
            GetData();//定义了一个GetData方法
            myplcData.CheckPlcConnectState(myplc);//引用了PlcData类下的方法用来判断PLC的连接状态
            stopwatch.Start();
        }

        void GetData()
        {
            //打开多线程
            Task.Run(() =>
            {
                while (true)
                {
                    Console.WriteLine(1111);
                    if (!myplc.IsConnected)//如果PLC连接失败，一直去连接plc
                    {
                        try
                        {
                            myplc.Open();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                    else
                    {
                        try//连接成功，把数据输出到textbox中
                        {
                            myplcData.db8_dbw24 = ((ushort)myplc.Read("DB8.DBW24")).ConvertToShort();
                            myplcData.db8_dbd12 = ((uint)myplc.Read("DB8.DBD12")).ConvertToFloat();
                            textBox1.Text = (myplcData.db8_dbw24).ToString();
                            textBox2.Text = myplcData.db8_dbd12.ToString();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                        }
                    }
                }
            }
            );
        }

        private void button2_Click(object sender, EventArgs e)
        {
            stopwatch.Stop();//计算两个按钮按下的时间间隔
            Console.WriteLine(stopwatch.ElapsedMilliseconds);
            MessageBox.Show((stopwatch.ElapsedMilliseconds/1000).ToString()+ "秒");
            
        }
    }
}
